package com.azunitech.apm.bundles.shell.commands;

import java.io.PrintStream;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import com.azunitech.apm.bundles.shell.BasicCommand;

/*
 * Lists the outstanding sessions and ephemeral nodes. This only works on the leader.
 */
public class CommandDUMP extends BasicCommand<BundleContext>
{
	private static final String CMD_KEY = "dump";
	private static final String CMD_DESC = "lists all bundles";
	
	public String getKey() 
	{
		return CommandDUMP.CMD_KEY;
	}

	public String getDesc() 
	{
		return CommandDUMP.CMD_DESC;
	}

	public void exec(String args, PrintStream out, PrintStream err)
			throws Exception 
	{
		BundleContext ctx = this.m_target;
		Bundle[] bundles = ctx.getBundles();
		for( Bundle bundle : bundles)
		{
			String msg = String.format("[%4d]", bundle.getBundleId());
			out.println(msg + " [" + getStateString(bundle.getState()) + "] " + bundle.getSymbolicName() + "(" + bundle.getVersion()+")");
			out.println("\r");
		}
	}
	
	private String getStateString(int state) {
	    switch (state) {
	      case Bundle.INSTALLED:
	        return "INSTALLED";
	      case Bundle.RESOLVED:
	        return "RESOLVED";
	      case Bundle.STARTING:
	        return "STARTING";
	      case Bundle.ACTIVE:
	        return "ACTIVE";
	      case Bundle.STOPPING:
	        return "STOPPING";
	      default:
	        return "UNKNOWN";
	    }
	  }
}
